﻿using System.Configuration;
using System.Drawing;
using System.IO;
using System.Web;
using ThoughtWorks.QRCode.Codec;

namespace AFT.Parking.Foundation.Utilities
{
    public static class QrCodeHelper
    {
        public static string GenerateQrcode(string controllerName, string tagId, string tagName = "")
        {
            var encoder = new QRCodeEncoder();
            encoder.QRCodeScale = 4;
            encoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            encoder.QRCodeVersion = 8;
            var baseUrl = ConfigurationSettings.AppSettings["Site"];
            var url = baseUrl + "/" + controllerName + "/" + "ScanView?tagId=" + tagId;
            Image img = encoder.Encode(url);
            return UploadQrcode(controllerName, img, tagName);
        }

        private static string UploadQrcode(string controllerName, Image img, string tagName)
        {
            var filename = tagName + ".jpg";
            var folder = HttpContext.Current.Server.MapPath(@"~\Upload\" + controllerName);

            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);

            var filepath = folder + "\\" + filename;

            FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write);
            img.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
            fs.Close();
            img.Dispose();

            return "/Upload/" + controllerName + "/" + filename;
        }
    }
}